package com.example.makerspace.service.impl;

import cn.hutool.core.lang.Dict;
import com.example.makerspace.dao.ImsingleDAO;
import com.example.makerspace.dao.OnlineUserListDAO;
import com.example.makerspace.domain.ImsingleDO;
import com.example.makerspace.domain.OnlineUserListDO;
import com.example.makerspace.dto.Result;
import com.example.makerspace.dto.robotDTO.ImsingleDTO;
import com.example.makerspace.mapper.ImsingleMapper;
import com.example.makerspace.service.CustomerService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CustomerServiceImpI implements CustomerService {
    @Resource
    private ImsingleMapper imsingleMapper;

    @Resource
    private ImsingleDAO imsingleDAO;

    @Resource
    private OnlineUserListDAO onlineUserListDAO;
        public List<ImsingleDO> findByUsername(String fromUser, String toUser) {
            List<ImsingleDO> list = imsingleMapper.findByUsername(fromUser, toUser);
           for(int i=0;i<list.size();i++){
               list.get(i).setReaded(1);
               imsingleDAO.updateById(list.get(i));
           }
            return list;
        }

        public Dict findUnReadNums(String toUsername) {
            List<ImsingleDO> list = imsingleMapper.findByToUsername(toUsername);
            Map<String, List<ImsingleDO>> collect = list.stream().collect(Collectors.groupingBy(ImsingleDO::getFromuser));
            Dict dict = Dict.create();
            collect.forEach((k,v) -> dict.set(k, v.size()));
            return dict;
        }

    @Override
    public Result insertMessage(ImsingleDTO imsingleDTO) {
        ImsingleDO imsingleDO = new ImsingleDO();
        BeanUtils.copyProperties(imsingleDTO,imsingleDO);
        imsingleMapper.insert(imsingleDO);
        return Result.success("发送成功!");
    }

    @Override
    public Result selectUserList() {
        List<OnlineUserListDO> onlineUserListDOS = onlineUserListDAO.selectAll();
        List<OnlineUserListDO> adminDO = onlineUserListDOS.stream().filter(item -> !item.equals("admin")).collect(Collectors.toList());
        return Result.success(adminDO);
    }

    @Override
    public Result stopSession(String fromUser) {
        imsingleMapper.deleteByFromUser(fromUser);
        return Result.success("结束通话");
    }
}
